<?php


namespace App\Repositories;


use Exception;
use LTools\Repositories\RepositoryAbstract;

class ProductInventory extends RepositoryAbstract
{
    /**
     * ProductInventory constructor.
     * @param \App\Models\ProductInventory $model
     */
    public function __construct(\App\Models\ProductInventory $model)
    {
        $this->model = $model;
    }

    /**
     * @param array $attributes
     * @param int|null $perPage
     * @param array $columns
     * @param string $pageName
     * @param int|null $page
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function paginate(array $attributes, int $perPage = null, array $columns = ['*'], $pageName = 'page', int $page = null)
    {
        return $this->model->with(['product', 'customer'])->where(
            $attributes
        )->paginate($perPage, $columns, $pageName, $page);
    }

    /**
     * @param $productId
     * @param $quantity
     * @throws \Throwable
     */
    public function lock($productId, $quantity){
        /** @var \App\Models\ProductInventory $model */
        try{
            // 这里用了锁
            $model = $this->model->where('product_id', '=', $productId)
                ->lockForUpdate()->firstOrFail();

            $model->usable = $model->usable - $quantity;
            $model->locked = $model->locked + $quantity;
            $model->saveOrFail();
        }catch (Exception $exception){
            throw new Exception('锁定库存失败，请检查库存是否充足！！');
        }
    }

    /**
     * @param $productId
     * @param $quantity
     * @return void
     * @throws \Throwable
     */
    public function unLock($productId, $quantity){
        /** @var \App\Models\ProductInventory $model */
        try{
            // 这里用了锁
            $model = $this->model->where('product_id', '=', $productId)
                ->lockForUpdate()->firstOrFail();

            $model->usable = $model->usable + $quantity;
            $model->locked = $model->locked - $quantity;
            $model->saveOrFail();
        }catch (Exception $exception){
            throw new Exception('库存解锁失败，请检查库存是否充足！！');
        }
    }
}
